package com.dingding.transfer.stamper.service.impl;

import cn.hutool.core.collection.ConcurrentHashSet;
import com.dingding.transfer.stamper.dao.UserDao;
import com.dingding.transfer.stamper.dto.BaseResult;
import com.dingding.transfer.stamper.dto.BaseResultFactory;
import com.dingding.transfer.stamper.dto.FingerAddRes;
import com.dingding.transfer.stamper.entity.ProcessDetail;
import com.dingding.transfer.stamper.entity.User;
import com.dingding.transfer.stamper.service.BusinessService;
import com.dingding.transfer.stamper.service.CmdStrategy;
import com.dingding.transfer.stamper.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;

/**
 * @author wangxiyuan 印章系统的回调
 * @description 指纹录入回调 录入指纹的时候会录入两遍指纹 这里回调函数会调用两次
 * @createDate 2021/4/6 11:12
 **/
@Slf4j
public class FingerAddResStrategy implements CmdStrategy {
    private static final Set<FingerAddRes> fingerSet = new ConcurrentHashSet<>();
    @Override
    public BaseResult handle(Object object) {
        FingerAddRes res = (FingerAddRes)object;
        if(res.isStatus()){
            log.info("指纹录入回调成功，用户ID为{}",res.getUserId());
            // 推送申请单
            synchronized (fingerSet){
                if(!fingerSet.contains(res) && res.isStatus()){
                    fingerSet.add(res);
                }else{
                    return BaseResultFactory.produceSuccess();
                }
            }
            BusinessService businessService = SpringContextUtil.getBean(BusinessService.class);
            UserDao userDao = SpringContextUtil.getBean(UserDao.class);
            User user = userDao.selectById(Integer.parseInt(res.getUserId()));
            ProcessDetail applyDetail = businessService.findApplyDetail(user.getUserid(),res.getUuid());
            if(applyDetail != null){
                int pushTime = 0;
                while(pushTime < 4){
                    BaseResult baseResult = businessService.pushRecord(res.getUuid(),applyDetail.getApplyId().toString());
                    if(baseResult.isSuccess()){
                        break;
                    }else{
                        pushTime++;
                    }
                }
            }
            return BaseResultFactory.produceSuccess();
        }
        return BaseResultFactory.produceError();
    }
}
